<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Message } from '@arco-design/web-vue'
import { getDishById, getDishSpecByDishId } from '@/api/dish'
import { getMerchantById } from '@/api/merchant'
import type { Dish, DishSpec } from '@/api/dish'
import type { Merchant } from '@/api/merchant'

const route = useRoute()
const router = useRouter()
const dishId = computed(() => Number(route.params.id))
const loading = ref(false)
const dish = ref<Dish | null>(null)
const merchant = ref<Merchant | null>(null)
const specs = ref<DishSpec[]>([])
const selectedSpec = ref<DishSpec | null>(null)
const quantity = ref(1)

// 初始化数据
onMounted(async () => {
  loading.value = true
  try {
    // 获取菜品信息
    const dishRes = await getDishById(dishId.value)
    if (dishRes.code === 200 && dishRes.data) {
      dish.value = dishRes.data
      
      // 获取商家信息
      const merchantRes = await getMerchantById(dish.value.merchantId)
      if (merchantRes.code === 200 && merchantRes.data) {
        merchant.value = merchantRes.data
      }
      
      // 获取菜品规格
      const specsRes = await getDishSpecByDishId(dishId.value)
      if (specsRes.code === 200 && specsRes.data) {
        specs.value = specsRes.data
        
        // 默认选择第一个规格
        if (specs.value && specs.value.length > 0) {
          selectedSpec.value = specs.value[0]
        }
      }
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    Message.error('加载数据失败，请稍后再试')
  } finally {
    loading.value = false
  }
})

// 计算当前价格
const currentPrice = computed(() => {
  if (!dish.value) return 0
  
  // 如果选择了规格，使用规格价格
  if (selectedSpec.value) {
    return selectedSpec.value.price
  }
  
  // 否则使用菜品价格（如果是特价菜品，使用特价）
  return dish.value.isSpecial ? (dish.value.specialPrice || dish.value.price) : dish.value.price
})

// 计算总价
const totalPrice = computed(() => {
  return currentPrice.value * quantity.value
})

// 选择规格
const selectSpec = (spec: DishSpec) => {
  selectedSpec.value = spec
}

// 增加数量
const increaseQuantity = () => {
  quantity.value++
}

// 减少数量
const decreaseQuantity = () => {
  if (quantity.value > 1) {
    quantity.value--
  }
}

// 添加到购物车
const addToCart = () => {
  if (!dish.value) return
  
  // 从localStorage获取购物车数据
  const cartKey = `cart_${dish.value.merchantId}`
  let cartItems = []
  const cartData = localStorage.getItem(cartKey)
  
  if (cartData) {
    try {
      cartItems = JSON.parse(cartData)
    } catch (e) {
      console.error('解析购物车数据失败:', e)
    }
  }
  
  // 构建购物车项
  const cartItem = {
    dishId: dish.value.id,
    dishSpecId: selectedSpec.value?.id,
    quantity: quantity.value
  }
  
  // 检查是否已存在相同菜品和规格
  const existingItemIndex = cartItems.findIndex(
    (item: any) => item.dishId === cartItem.dishId && item.dishSpecId === cartItem.dishSpecId
  )
  
  if (existingItemIndex !== -1) {
    // 如果已存在，更新数量
    cartItems[existingItemIndex].quantity += cartItem.quantity
  } else {
    // 如果不存在，添加新项
    cartItems.push(cartItem)
  }
  
  // 保存到localStorage
  localStorage.setItem(cartKey, JSON.stringify(cartItems))
  
  Message.success('已添加到购物车')
}

// 立即购买
const buyNow = () => {
  addToCart()
  router.push(`/merchant/${dish.value?.merchantId}`)
}

// 返回商家页面
const goBackToMerchant = () => {
  if (dish.value) {
    router.push(`/merchant/${dish.value.merchantId}`)
  } else {
    router.push('/')
  }
}
</script>

<template>
  <div class="dish-detail-container">
    <a-spin :loading="loading" tip="加载中...">
      <!-- 返回按钮 -->
      <div class="back-button">
        <a-button shape="circle" @click="goBackToMerchant">
          <template #icon><icon-left /></template>
        </a-button>
      </div>

      <!-- 菜品信息 -->
      <div v-if="dish" class="dish-info">
        <div class="dish-image">
          <img :src="'https://materials.cdn.bcebos.com/images/39275436/26649005146a34c5ba54ba695f238091.jpeg'" alt="菜品图片" />
          <div v-if="dish.isSpecial" class="dish-tag special">特价</div>
          <div v-if="dish.isRecommended" class="dish-tag recommended">推荐</div>
        </div>
        
        <div class="dish-details">
          <h1>{{ dish.name }}</h1>
          
          <div class="dish-price">
            <span class="current-price">¥{{ currentPrice.toFixed(2) }}</span>
            <span v-if="dish.isSpecial && !selectedSpec" class="original-price">¥{{ dish.price }}</span>
          </div>
          
          <div class="dish-merchant" @click="goBackToMerchant">
            <a-avatar size="small">
              <template #icon><icon-shop /></template>
            </a-avatar>
            <span>{{ merchant?.name }}</span>
            <icon-right />
          </div>
          
          <div class="dish-description">
            <p>{{ dish.description }}</p>
          </div>
        </div>
      </div>

      <!-- 规格选择 -->
      <div v-if="specs.length > 0" class="dish-specs">
        <h3>规格</h3>
        <div class="specs-list">
          <a-tag
            v-for="spec in specs"
            :key="spec.id"
            checkable
            :checked="selectedSpec?.id === spec.id"
            @click="selectSpec(spec)"
          >
            {{ spec.name }} ¥{{ spec.price }}
          </a-tag>
        </div>
      </div>

      <!-- 数量选择 -->
      <div class="dish-quantity">
        <h3>数量</h3>
        <div class="quantity-selector">
          <a-button shape="circle" @click="decreaseQuantity" :disabled="quantity <= 1">
            <template #icon><icon-minus /></template>
          </a-button>
          <span class="quantity-value">{{ quantity }}</span>
          <a-button shape="circle" @click="increaseQuantity">
            <template #icon><icon-plus /></template>
          </a-button>
        </div>
      </div>

      <!-- 底部操作栏 -->
      <div class="bottom-bar">
        <div class="total-price">
          <span>总计：</span>
          <span class="price">¥{{ totalPrice.toFixed(2) }}</span>
        </div>
        <div class="actions">
          <a-button type="outline" size="large" @click="addToCart">加入购物车</a-button>
          <a-button type="primary" size="large" @click="buyNow">立即购买</a-button>
        </div>
      </div>
    </a-spin>
  </div>
</template>

<style scoped>
.dish-detail-container {
  padding-bottom: 60px;
  max-width: 1000px;
  margin: 0 auto;
}

.back-button {
  position: fixed;
  top: 70px;
  left: 16px;
  z-index: 10;
}

.dish-info {
  margin-bottom: 20px;
  display: flex;
  flex-direction: column;
  background-color: var(--bg-color-light);
  border-radius: var(--border-radius-md);
  box-shadow: var(--box-shadow-light);
  overflow: hidden;
}

.dish-image {
  position: relative;
  width: 100%;
  height: 400px;
  overflow: hidden;
}

.dish-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.dish-tag {
  position: absolute;
  top: 16px;
  left: 16px;
  padding: 6px 12px;
  font-size: 14px;
  color: #fff;
  border-radius: var(--border-radius-sm);
  font-weight: bold;
}

.dish-tag.special {
  background-color: var(--danger-color);
}

.dish-tag.recommended {
  background-color: var(--warning-color);
}

.dish-details {
  padding: 24px;
}

.dish-details h1 {
  margin: 0 0 20px 0;
  font-size: 28px;
  font-weight: bold;
}

.dish-price {
  display: flex;
  align-items: baseline;
  gap: 12px;
  margin-bottom: 20px;
}

.current-price {
  font-size: 28px;
  font-weight: bold;
  color: var(--danger-color);
}

.original-price {
  font-size: 18px;
  color: var(--text-disabled);
  text-decoration: line-through;
}

.dish-merchant {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 20px;
  padding: 12px 0;
  border-top: 1px solid var(--border-color);
  border-bottom: 1px solid var(--border-color);
  cursor: pointer;
}

.dish-description {
  margin-bottom: 20px;
  color: var(--text-secondary);
  font-size: 16px;
  line-height: 1.6;
}

.dish-specs {
  padding: 0 24px;
  margin-bottom: 30px;
  background-color: var(--bg-color-light);
  border-radius: var(--border-radius-md);
  box-shadow: var(--box-shadow-light);
  padding-top: 20px;
  padding-bottom: 20px;
}

.dish-specs h3 {
  margin: 0 0 16px 0;
  font-size: 18px;
  font-weight: bold;
}

.specs-list {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.specs-list .arco-tag {
  padding: 8px 16px;
  font-size: 16px;
  cursor: pointer;
}

.dish-quantity {
  padding: 0 24px;
  margin-bottom: 30px;
  background-color: var(--bg-color-light);
  border-radius: var(--border-radius-md);
  box-shadow: var(--box-shadow-light);
  padding-top: 20px;
  padding-bottom: 20px;
}

.dish-quantity h3 {
  margin: 0 0 16px 0;
  font-size: 18px;
  font-weight: bold;
}

.quantity-selector {
  display: flex;
  align-items: center;
  gap: 20px;
}

.quantity-value {
  width: 50px;
  text-align: center;
  font-size: 18px;
  font-weight: bold;
}

.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  background-color: var(--bg-color-light);
  border-top: 1px solid var(--border-color);
  z-index: 10;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
}

.total-price {
  font-size: 18px;
}

.total-price .price {
  font-size: 24px;
  font-weight: bold;
  color: var(--danger-color);
}

.actions {
  display: flex;
  gap: 16px;
}

.actions .arco-btn {
  padding: 0 24px;
  height: 44px;
  font-size: 16px;
}

/* 响应式调整 */
@media (min-width: 768px) {
  .dish-info {
    flex-direction: row;
  }
  
  .dish-image {
    width: 50%;
    height: auto;
  }
  
  .dish-details {
    width: 50%;
  }
}
</style> 